import { useStore } from 'vuex'
import { computed, watch, ref } from 'vue'
import { getLyric } from '@/service/song'
// 作何的解析Lyric插件
import Lyric from 'lyric-parser'

export default function useLyric (songReady, currentTime) {
  // 当前歌词对象，会经过lyric-parser处理
  const currentLyric = ref(null)
  // 当前歌词行号
  const currentLineNum = ref(0)
  const lyricScrollRef = ref(null)
  const pureMusicLyric = ref('')
  const lyricListRef = ref(null)
  //   当前歌词
  const playingLyric = ref('')
  const store = useStore()
  const currentSong = computed(() => store.getters.currentSong)

  watch(currentSong, async (newSong) => {
    if (!newSong.url || !newSong.id) {
      return
    }
    stopLyric()
    currentLyric.value = null
    currentLineNum.value = 0
    playingLyric.value = ''

    const lyric = await getLyric(newSong)
    store.commit('addSongLyric', { song: newSong, lyric })
    if (currentSong.value.lyric !== lyric) {
      return
    }
    // 每次换行歌词，都会执行handleLyric
    currentLyric.value = new Lyric(lyric, handleLyric)
    // 根据是否有长度，判断是否有歌词
    const hasLyric = currentLyric.value.lines.length
    if (hasLyric) {
      if (songReady.value) {
        playLyric()
      }
    } else {
      pureMusicLyric.value = lyric.slice(0, 10)
    }
  })

  function handleLyric ({ lineNum, txt }) {
    currentLineNum.value = lineNum
    playingLyric.value = txt
    const scrollComp = lyricScrollRef.value
    const listEl = lyricListRef.value
    if (!listEl) {
      return
    }
    if (lineNum > 6) {
      const lineEl = listEl.children[lineNum - 6]
      scrollComp.scroll.scroll._value.scrollToElement(lineEl, 1000)
    } else {
      scrollComp.scroll.scroll._value.scrollTo(0, 0, 1000)
    }
  }

  // 滚动歌词
  function playLyric () {
    const currentLyricVal = currentLyric.value
    if (currentLyricVal) {
      // 定位到currentTime的歌词开始滚动歌词，但这个滚动不受audio的暂停控制
      currentLyricVal.seek(currentTime.value * 1000)
    }
  }
  // 暂停滚动歌词
  function stopLyric () {
    const currentLyricVal = currentLyric.value
    if (currentLyricVal) {
      // 定位到currentTime的歌词开始滚动歌词，但这个滚动不受audio的暂停控制
      currentLyricVal.stop()
    }
  }

  return {
    lyricScrollRef,
    lyricListRef,
    currentLyric,
    currentLineNum,
    playingLyric,
    pureMusicLyric,
    playLyric,
    stopLyric
  }
}
